var exec = require("child_process").exec,
    Q = require('q');

var errorCallback = function(err) {
    console.log("error : " + err);
};

var svnCommand = "svn";

exports.isAvailable = function() {
    var defer = Q.nfcall(exec, [svnCommand, "--version"].join(" "));
    defer.fail(errorCallback);
    defer.then(function() {
        console.log("succeed : svn is available");
    });
    return defer;
};

exports.cleanup = function(path) {
    var defer = Q.nfcall(exec, [svnCommand, "cleanup", path].join(" "));
    defer.fail(errorCallback);
    defer.then(function() {
        console.log("succeed : svn cleanup " + path);
    });
    return defer;
};

exports.checkout = function(url, target) {
    console.log("processing : svn checkout " + url + " to " + target);
    var command = [svnCommand, "checkout", url, target, "--username",
        "kamliao"].join(" "),
        defer = Q.nfcall(exec, command);
    defer.fail(errorCallback);
    defer.then(function() {
        console.log("succeed : svn checkout " + url + " to " + target);
    });
    return defer;
};

exports.copy = function(src, target, msg) {
    msg = msg || '"test copy"';
    var command = [svnCommand, "copy", src, target, "-m", msg].join(" "),
        defer = Q.nfcall(exec, command);
    defer.fail(errorCallback);
    defer.then(function() {
        console.log("succeed : svn copy " + src + " to " + target);
    });
    return defer;
};

exports.commit = function(path, msg) {
    var command = [svnCommand, "commit", path, "-m", msg, "--username",
        "kamliao"].join(" "),
        defer = Q.nfcall(exec, command);
    defer.fail(errorCallback);
    defer.then(function() {
        console.log("succeed : svn commit " + path);
    });
    return defer;
};

exports.add = function(path) {
    var command = [svnCommand, "add", path].join(" "),
        defer = Q.nfcall(exec, command);
    defer.fail(errorCallback);
    defer.then(function() {
        console.log("succeed : svn add " + path);
    });
    return defer;
};

exports.stat = function(path) {
    var command = [svnCommand, "stat", path].join(" "),
        defer = Q.nfcall(exec, command);
    defer.fail(errorCallback);
    return defer;
};